import { supabase } from "./supabase";
import CryptoJS from 'crypto-js';
import type { Session, AuthChangeEvent } from '@supabase/supabase-js';
const encryptMD5 = (text: string): string => {
    return CryptoJS.MD5(text).toString();
}
export const getUser = async () => {
    const { data: { user } } = await supabase.auth.getUser();
    return user;
};

export const getUserProfile = async ({ key, val }: { key: string, val: string }) => {
    const data = await supabase.from('user_profiles')
        .select('*')
        .eq(key, val)
        .single();
    return data;
};

export const signOut = async () => {
    const { error } = await supabase.auth.signOut();
    return { error };
};

export const signInWithEmail = async (email: string, password: string) => {
    // 使用MD5加密密码
    const encryptedPassword = encryptMD5(password);
    const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password: encryptedPassword,
    });
    return { data, error };
};

export const signUpWithEmail = async (email: string, password: string) => {
    // 使用MD5加密密码
    const encryptedPassword = encryptMD5(password);
    const { data, error } = await supabase.auth.signUp({
        email,
        password: encryptedPassword,
    });
    return { data, error };
};

export const resetPassword = async (email: string) => {
    const { data, error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: `${window.location.origin}/auth/reset-password`,
    });
    return { data, error };
};

export const updatePassword = async (newPassword: string) => {
    // 使用MD5加密新密码
    const encryptedPassword = encryptMD5(newPassword);
    const { data, error } = await supabase.auth.updateUser({
        password: encryptedPassword,
    });
    return { data, error };
};

// 获取当前会话
export const getSession = async () => {
    const { data: { session }, error } = await supabase.auth.getSession();
    return { session, error };
};
// 谷歌账号登陆
export const googleSignIn = async () => {
    const { data, error } = await supabase.auth.signInWithOAuth({
        provider: 'google',
        options: {
            redirectTo: `${window.location.origin}/dashboard`
        }
    });
    return { data, error };
};
// 设置会话状态变更监听器
export const onAuthStateChange = (
    callback: (event: AuthChangeEvent, session: Session | null) => void
) => {
    return supabase.auth.onAuthStateChange((event, session) => {
        callback(event, session);
    });
};
